Introduction to Python Day 3

Verjinia Metodieva and Daniel Parthier

2025-02-18

Index based for loops - range()

  • generates integer sequences
  • range(n) generates the series of n values from 0 to n − 1
<<<<<<< HEAD
=======
>>>>>>> 3e0ab13596212d4fe960010623ecb46bed21d94b
for i in range(5):
    print(i)
0
1
2
3
4
<<<<<<< HEAD
=======
>>>>>>> 3e0ab13596212d4fe960010623ecb46bed21d94b
# looping through data indices. find the max
B = [1, 4, 6, 7, 89, 54]
big_indx = 0
for i in range(len(B)):
    if B[i] > B[big_indx]:
        big_indx = i
print('The max value in B is', B[big_indx], 'found on position', big_indx)
The max value in B is 89 found on position 4

Index based for loops - enumerate()

  • assigns a count to each item within an iterable and returns it as an enumerate object
  • one way to avoid nested loops
<<<<<<< HEAD
=======
>>>>>>> 3e0ab13596212d4fe960010623ecb46bed21d94b
import numpy as np

array_a = np.arange(20, 25)
for indx, val in enumerate(array_a):
    print('the index is', indx)
    print('the value is', val)
the index is 0
the value is 20
the index is 1
the value is 21
the index is 2
the value is 22
the index is 3
the value is 23
the index is 4
the value is 24

! range() and enumerate() - none of the two returns a list of objects!

Break and continue statements

  • break - immediately terminates the loop
  • continue - skips whatever is after it and continues with the next iteration
    • mostly used after a conditional statement

While loops

  • Perform a task while something is True
  • Be careful:
    • Some loops never finish (get stuck)
    • Make sure that condition for ending the loop can be fullfilled
while check_condition:
    perform_task()

Let’s wait while we wait

  • Start a little counter
import time
counter = 0
while counter < 10:
    time.sleep(1)
    counter += 1
    print("You waited for " + str(counter) + " seconds...")
  • Good for keeping processes running

Errors and how to read them

There are useful resources regarding errors

  • Simply googling works surprisingly well
  • You will often end up on stackoverflow
    • There is no question which was not already asked1

Types of errors

  1. SyntaxErrors
  2. IndentationError
  3. NameError
  4. TypeError
  5. IndexError
  6. AttributeError
  7. etc.

Fix errors

  • Breath
  • Don’t panic
    • Identify the error by checking the terminal output
    • Look at the line provided
    • Go backwards if error is nested